package com.bank.controller;

import com.bank.common.Result;
import com.bank.entity.Deposit;
import com.bank.mapper.DepositMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

/**
 * 存款类型控制器
 */
@RestController
@RequestMapping("/api/deposit")
public class DepositController {

    @Autowired
    private DepositMapper depositMapper;

    /**
     * 查询所有存款类型
     */
    @GetMapping("/list")
    public List<Deposit> list() {
        return depositMapper.findAll();
    }

    /**
     * 新增存款类型
     */
    @PostMapping
    public int add(@RequestBody Deposit deposit) {
        return depositMapper.insert(deposit);
    }

    /**
     * 修改存款类型
     */
    @PutMapping
    public int update(@RequestBody Deposit deposit) {
        return depositMapper.update(deposit);
    }

    /**
     * 删除存款类型
     */
    @DeleteMapping("/{savingID}")
    public int delete(@PathVariable Integer savingID) {
        return depositMapper.deleteById(savingID);
    }

    /**
     * 模糊查询存款类型
     */
    @GetMapping("/search")
    public Result<List<Deposit>> search(
            @RequestParam(required = false) Integer exactId,
            @RequestParam(required = false) String keyword) {

        if (exactId != null) {
            // 精确查询
            Deposit deposit = depositMapper.findById(exactId);
            return Result.success(deposit != null ? Collections.singletonList(deposit) : Collections.emptyList());
        } else if (keyword != null && !keyword.isEmpty()) {
            // 模糊查询
            return Result.success(depositMapper.searchByKeyword("%" + keyword + "%"));
        } else {
            // 无查询条件，返回所有数据
            return Result.success(depositMapper.findAll());
        }
    }
}